import React, { useEffect, useRef, useState } from 'react'
import './style.css'
import av from '../../assets/images/robot-avatar.jpg'
import { useAppSelector } from '../../store/hooks'
import { getHttp } from '../../api'

interface ListHistoryState {
  _id: string,
  from: string | null,
  to: string | null,
  content: string,
  createdAt: number
}

const Index: React.FC = () => {
  const avator = useAppSelector(state => state.user.userInfo.headPic);
  const input = useRef<null | HTMLInputElement>(null)
  const [list, setList] = useState<ListHistoryState[]>([])
  const container = useRef<null | HTMLDivElement>(null)
  const token = sessionStorage.getItem('token')
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const content = input.current?.value;
    if (content) {
      setList(list => [...list, {
        "_id": "652269ebf507257e7719a030",
        "from": "906446244",
        "to": null,
        "content": content,
        "createdAt": new Date().getTime()
      }])
      getHttp('/xxx/chat/robot', { content }, { token }).then(resp => {
        setList(list => [...list, {
          "_id": "652269edf507257e7719a032",
          "from": null,
          "to": "906446244",
          "content": resp.result,
          "createdAt": 1696754157864
        }])
      })
    }
  }

  useEffect(() => {
    getHttp('/xxx/chat/history', {}, { token: token }).then(resp => {
      setList(resp.result)
    })
  }, [])

  useEffect(() => {
    if (container.current) {
      container.current.scrollTop =
        container.current.scrollHeight;
    }
  }, [list])


  return (
    <div className="main">
      <h1 className="main-title">
        <img src={av} alt="" />
        AI 聊天机器人
      </h1>
      <div className="chat-container" ref={container}>
        {
          list.map((v, i) => {
            if (v.from) {
              return <div className="chat-item me" key={i}>
                <img className="chat-avatar" src={avator} />
                <div className="chat-content">{v.content}</div>
                {/* <div className="chat-date">2022-04-29 14:18:13</div> */}
              </div>
            } else {
              return <div className="chat-item" key={i}>
                <img className="chat-avatar" src={av} />
                <div className="chat-content">{v.content}</div>
                {/* <div className="chat-date">2022-04-29 14:18:16</div> */}
              </div>
            }
          })
        }



      </div>
      <form className="msg-container" onSubmit={(e) => handleSubmit(e)}>
        <input ref={input} type="text" id="txtMsg" placeholder="在这里输入要发送的消息，按回车键即可发送" name='content' />
        <button>发送</button>
      </form>
    </div>
  )
}

export default Index